package com.example.myapplicationwork.repository;

import android.content.Context;
import android.util.Log;

import com.example.myapplicationwork.model.LoginRequest;
import com.example.myapplicationwork.model.LoginResponse;
import com.example.myapplicationwork.model.RegisterRequest;
import com.example.myapplicationwork.model.RegisterResponse;
import com.example.myapplicationwork.model.UserResponse;
import com.example.myapplicationwork.network.NetworkUtils;
import com.example.myapplicationwork.utils.SharedPreferencesUtil;
import com.google.gson.Gson;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 认证仓库
 * 处理登录、注册和自动登录等网络请求
 */
public class AuthRepository {
    private static final String TAG = "AuthRepository";
    private static final String BASE_URL = "https://reqres.in/api";
    private static final String LOGIN_URL = BASE_URL + "/login";
    private static final String REGISTER_URL = BASE_URL + "/register";
    private static final String AUTO_LOGIN_URL = BASE_URL + "/auto-login";
    private static final String USER_URL = BASE_URL + "/users/2"; // 模拟用户信息接口

    private final ExecutorService executorService;
    private final Gson gson;
    private final SharedPreferencesUtil preferencesUtil;

    public AuthRepository(Context context) {
        executorService = Executors.newSingleThreadExecutor();
        gson = new Gson();
        preferencesUtil = SharedPreferencesUtil.getInstance(context);
    }

    /**
     * 登录请求
     */
    public void login(LoginRequest request, LoginCallback callback) {
        executorService.execute(() -> {
            try {
                String jsonRequest = gson.toJson(request);
                Log.d(TAG, "登录请求: " + jsonRequest);
                String response = NetworkUtils.postRequest(LOGIN_URL, jsonRequest);
                Log.d(TAG, "登录响应: " + response);
                Log.d(TAG, "响应长度: " + (response != null ? response.length() : 0));
                Log.d(TAG, "响应是否包含token: " + (response != null && response.contains("token")));
                Log.d(TAG, "响应是否包含error: " + (response != null && response.contains("error")));

                // 检查响应是否为空或包含错误信息
                if (response == null || response.isEmpty()) {
                    Log.e(TAG, "响应为空，返回失败");
                    callback.onFailure("登录失败，服务器未返回数据");
                    return;
                }

                LoginResponse loginResponse = gson.fromJson(response, LoginResponse.class);
                Log.d(TAG, "解析后的LoginResponse: " + (loginResponse != null ? 
                        "token=" + loginResponse.getToken() + ", error=" + loginResponse.getError() : "null"));

                if (loginResponse != null) {
                    Log.d(TAG, "isSuccess()结果: " + loginResponse.isSuccess());
                    // 即使token存在，也要检查是否有error字段
                    if (loginResponse.isSuccess() && loginResponse.getError() == null) {
                        Log.d(TAG, "登录成功，准备获取用户信息");
                        // 登录成功后，获取用户信息
                        fetchUserInfo(loginResponse.getToken(), callback);
                    } else {
                        String errorMessage = loginResponse.getError() != null ? 
                                loginResponse.getError() : "登录失败，请检查邮箱和密码";
                        Log.e(TAG, "登录失败，错误信息: " + errorMessage);
                        callback.onFailure(errorMessage);
                    }
                } else {
                    // 尝试直接检查响应是否包含错误信息
                    if (response.contains("error")) {
                        Log.e(TAG, "响应包含error字段，返回失败");
                        callback.onFailure("登录失败，凭据无效");
                    } else {
                        Log.e(TAG, "无效的JSON响应，返回失败");
                        callback.onFailure("登录失败，服务器返回无效数据");
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "登录异常", e);
                callback.onFailure("登录失败：" + e.getMessage());
            }
        });
    }

    /**
     * 注册请求
     */
    public void register(RegisterRequest request, RegisterCallback callback) {
        executorService.execute(() -> {
            try {
                String jsonRequest = gson.toJson(request);
                Log.d(TAG, "注册请求: " + jsonRequest);
                String response = NetworkUtils.postRequest(REGISTER_URL, jsonRequest);
                Log.d(TAG, "注册响应: " + response);

                RegisterResponse registerResponse = gson.fromJson(response, RegisterResponse.class);

                if (registerResponse != null) {
                    if (registerResponse.isSuccess()) {
                        // 注册成功后，模拟用户信息
                        String userId = String.valueOf(registerResponse.getId());
                        String token = registerResponse.getToken();
                        String email = request.getEmail();
                        String userName = "User" + userId;
                        
                        callback.onSuccess(token, email, userId, userName);
                    } else {
                        String errorMessage = registerResponse.getError() != null ? 
                                registerResponse.getError() : "注册失败，请检查网络连接";
                        callback.onFailure(errorMessage);
                    }
                } else {
                    callback.onFailure("注册失败，服务器返回无效数据");
                }
            } catch (Exception e) {
                Log.e(TAG, "注册异常", e);
                callback.onFailure("注册失败：" + e.getMessage());
            }
        });
    }

    /**
     * 自动登录请求
     */
    /**
     * 自动登录请求
     */
    public void autoLogin(AutoLoginCallback callback) {
        executorService.execute(() -> {
            try {
                String token = preferencesUtil.getToken();
                if (token == null || token.isEmpty()) {
                    callback.onFailure("未找到登录凭据");
                    return;
                }

                // 注意：根据API文档，reqres.in没有auto-login端点
                // 这里使用获取用户信息的方式来验证Token有效性
                String url = USER_URL + "?token=" + token;
                String response = NetworkUtils.getRequest(url);
                Log.d(TAG, "自动登录响应: " + response);

                UserResponse userResponse = gson.fromJson(response, UserResponse.class);

                if (userResponse != null && userResponse.isSuccess()) {
                    String userId = userResponse.getData().getId();
                    String email = userResponse.getData().getEmail();
                    String userName = userResponse.getData().getFullName();
                    
                    callback.onSuccess(token, email, userId, userName);
                } else {
                    // 如果Token无效，返回失败
                    callback.onFailure("Token已过期，请重新登录");
                }
            } catch (Exception e) {
                Log.e(TAG, "自动登录异常", e);
                callback.onFailure("自动登录失败：" + e.getMessage());
            }
        });
    }

    /**
     * 刷新Token
     */
    public void refreshToken(TokenRefreshCallback callback) {
        executorService.execute(() -> {
            try {
                // 注意：根据API文档，reqres.in没有refresh-token端点
                // 这里使用模拟的方式处理Token刷新
                // 实际应用中应该调用真实的刷新Token接口
                Thread.sleep(500); // 模拟网络延迟
                
                // 检查是否有保存的用户邮箱和密码用于刷新Token
                String email = preferencesUtil.getUserEmail();
                if (email != null) {
                    // 使用模拟的密码进行重新登录
                    LoginRequest request = new LoginRequest(email, "password");
                    String jsonRequest = gson.toJson(request);
                    String response = NetworkUtils.postRequest(LOGIN_URL, jsonRequest);
                    
                    LoginResponse loginResponse = gson.fromJson(response, LoginResponse.class);
                    if (loginResponse != null && loginResponse.isSuccess()) {
                        fetchUserInfo(loginResponse.getToken(), new LoginCallback() {
                            @Override
                            public void onSuccess(String token, String email, String userId, String userName) {
                                callback.onSuccess(token);
                            }

                            @Override
                            public void onFailure(String errorMessage) {
                                callback.onFailure(errorMessage);
                            }
                        });
                        return;
                    }
                }
                
                callback.onFailure("Token已过期，请重新登录");
            } catch (Exception e) {
                Log.e(TAG, "刷新Token异常", e);
                callback.onFailure("刷新Token失败：" + e.getMessage());
            }
        });
    }

    /**
     * 获取用户信息
     */
    private void fetchUserInfo(String token, LoginCallback callback) {
        try {
            // 使用固定的用户ID获取用户信息
            String url = USER_URL + "?token=" + token;
            String response = NetworkUtils.getRequest(url);
            Log.d(TAG, "用户信息响应: " + response);

            UserResponse userResponse = gson.fromJson(response, UserResponse.class);

            if (userResponse != null && userResponse.isSuccess()) {
                String userId = userResponse.getData().getId();
                String email = userResponse.getData().getEmail();
                String userName = userResponse.getData().getFullName();
                
                callback.onSuccess(token, email, userId, userName);
            } else {
                // 获取用户信息失败，调用失败回调
                callback.onFailure("获取用户信息失败，请检查登录凭据");
            }
        } catch (Exception e) {
            Log.e(TAG, "获取用户信息异常", e);
            // 异常情况下，调用失败回调
            callback.onFailure("获取用户信息异常：" + e.getMessage());
        }
    }

    /**
     * 登录回调接口
     */
    public interface LoginCallback {
        void onSuccess(String token, String email, String userId, String userName);
        void onFailure(String errorMessage);
    }

    /**
     * 注册回调接口
     */
    public interface RegisterCallback {
        void onSuccess(String token, String email, String userId, String userName);
        void onFailure(String errorMessage);
    }

    /**
     * 自动登录回调接口
     */
    public interface AutoLoginCallback {
        void onSuccess(String token, String email, String userId, String userName);
        void onFailure(String errorMessage);
    }

    /**
     * Token刷新回调接口
     */
    public interface TokenRefreshCallback {
        void onSuccess(String newToken);
        void onFailure(String errorMessage);
    }
}